﻿using System;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Windows;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using KlavoNotifications.Fetch;
using KlavoNotifications.Utils;
using KlavoNotifications.ViewModels.Notification;
using KlavoNotifications.Views.Notification;
using Microsoft.Practices.Prism.Commands;
using System.Linq;

namespace KlavoNotifications.ViewModels.Tray
{
    public class TrayListViewModel : GamesListViewModel
    {        
        private readonly DelegateCommand _quitCommand;
        private bool _isRunning;

        public TrayListViewModel()
        {           
            _quitCommand = new DelegateCommand(QuitCommandExecuted);
            Fetcher fetcher = App.Get<Fetcher>();
            if (fetcher != null)
            {
                if (!fetcher.IsStarted)
                {
                    fetcher.Start();
                }
                fetcher.FetchDataComleted += FetchDataComleted;
            }
        }
      
        public DelegateCommand QuitCommand
        {
            get { return _quitCommand; }
        }

        public bool IsRunning
        {
            get { return _isRunning; }
            set
            {
                _isRunning = value;

                Fetcher fetcher = App.Get<Fetcher>();
                if (fetcher == null) return;

                TaskBar taskBar = App.Get<TaskBar>();
                if (taskBar == null) return;

                _items.Clear();

                if (fetcher.IsStarted)
                {
                    fetcher.Stop();
                    taskBar.SetStoppedState();
                }
                else
                {
                    fetcher.Start();
                    taskBar.SetRunningState();
                }
            }
        }

        void FetchDataComleted(FetchData data)
        {
            _timer.Stop();
            _items.Clear();

            foreach (var xGame in data.Games)
            {
                TrayItemViewModel item = ItemFromData(xGame, data.Timestamp);
                if (item != null)
                    _items.Add(item);
            }
            _timer.Start();
        }      

        private void QuitCommandExecuted()
        {
            Application.Current.Shutdown();
        }     
    }
}